﻿using System;
using System.Threading;
using System.Windows.Forms;
using Ninject.Core;
using Odin.Contracts.Data;
using Odin.Contracts.Services;
using Odin.Execution.Client;

namespace Odin.Execution.Services
{
	public class BrowserService : IBrowserService
	{
		public event EventHandler Navigated = (s, e) => { };

		private Session _session;
		private Thread _thread;

		public void Navigate(Session session)
		{
			_session = session;
			_thread = new Thread(FormThread);
			_thread.SetApartmentState(ApartmentState.STA);
			_thread.Start();
		}

		public void ShutDown(Session session)
		{
			_thread.Abort();
		}

		[Inject]
		public IWebServer WebServer { get; set; }


		private string GetUrl()
		{
			var url = string.Format("{0}/{1}?{2}={3}", WebServer.BaseUrl, Core.TestPage,Session.SessionIdentifierKey,_session.Identifier);
			return url;
		}

		private void FormThread()
		{
			var form = new BrowserForm();
			form.DocumentCompleted += FormDocumentCompleted;
			form.Show();
			var url = GetUrl();
			form.Navigate(url);
			Application.Run(form);
		}

		private void FormDocumentCompleted(object sender, EventArgs e)
		{
			Navigated(sender, e);
		}
	}
}
